package com.css.apps.base.role.action;

import com.css.apps.base.log.model.LogConstant;
import com.css.apps.base.log.model.LogPart;
import com.css.apps.base.role.model.SRole;
import com.css.apps.base.user.model.SUser;
import com.css.apps.base.user.model.SUserRole;
import com.css.apps.base.user.service.UserHelper;
import com.css.core.configuration.Environment;
import com.css.db.query.QueryCache;
import com.css.db.query.TransactionCache;
import com.css.util.*;
import com.css.webbase.webwork.action.AdminAction;
import com.opensymphony.xwork.Action;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.ArrayList;
import java.util.List;

@SuppressWarnings("serial")
public class AddRoleUser extends AdminAction {
	
	private static Log log = LogFactory.getLog(AddRoleUser.class);
	private String roleId;
	// private String userIds;
	private String orgids;
	private String ids;

	public String adminGo() {
		TransactionCache tx = null;
		try {
			if (StringHelper.isEmpty(roleId) || StringHelper.isEmpty(ids) || StringHelper.isEmpty(orgids)) {
				result = Ajax.JSONResult(Environment.RESULT_CODE_ERROR, Messages.getString("systemMsg.idsEmpty"));
				return Action.ERROR;
			}
			SRole sRole = QueryCache.get(SRole.class, roleId);
			List<String> userIdList = StringHelper.strToList(ids);
			List<String> orgIdList = StringHelper.strToList(orgids);
			List<SUserRole> roles = new ArrayList<SUserRole>();
			for (int i = 0; i < userIdList.size() && i < orgIdList.size(); i++) {
				String userId = userIdList.get(i);
				String sysid = orgIdList.get(i);
				if (StringHelper.isNotEmpty(userId) && StringHelper.isNotEmpty(sysid)) {
					SUserRole userrole = new SUserRole();
					userrole.setRoleId(roleId);
					userrole.setSysId(sRole.getSysId());
					userrole.setUserId(userId);
					userrole.setUuid(UuidUtil.getUuid());
					roles.add(userrole);
					SUser user = QueryCache.get(SUser.class, userId);
					user.getRoleList().add(roleId);
				}
			}
			addDeskRole(sRole, userIdList);
			tx = new TransactionCache();
			tx.save(roles);
			tx.commit();

			UserHelper helper = new UserHelper();
			for (SUserRole userrole : roles) {
				LogPart lp = new LogPart();
				lp.setOpObjType(SUserRole.class.getName());
				lp.setOpObjId(userrole.getUuid());
				lp.setRelObjType(SRole.class.getName());
				lp.setRelObjId(roleId);
				lp.setOpType(LogConstant.LOG_TYPE_ADD);
				lp.setLogLevel(LogConstant.LOG_LEVEL_COMMON);
				lp.setLogData(Json.object2json(userrole));
				lp.setResult(LogConstant.RESULT_SUCCESS);
				lp.save();
				helper.clearUserMenuCache(userrole.getUserId());
			}
			result = Ajax.JSONResult(Environment.RESULT_CODE_SUCCESS, Messages.getString("systemMsg.success"));
			return Action.SUCCESS;
		} catch (Exception ex) {
			if (tx != null) {
				tx.rollback();
			}
			result = Ajax.JSONResult(Environment.RESULT_CODE_ERROR, Messages.getString("systemMsg.exception"));
			log.error(ex.getMessage(), ex);
			return Action.ERROR;
		}
	}

	public String getRoleId() {
		return roleId;
	}

	public void setRoleId(String roleId) {
		this.roleId = roleId;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public String getOrgids() {
		return orgids;
	}

	public void setOrgids(String orgids) {
		this.orgids = orgids;
	}

	@SuppressWarnings("unchecked")
	public void addDeskRole(SRole sRole, List<String> userIdList) {
		List<String> addSys = new ArrayList<>();
		// 循环取用户所具有的sysId列表
		for (String userId : userIdList) {
			QueryCache qc = new QueryCache("select DISTINCT a.sysId from SUserRole a  where a.userId=:userId ")
					.setParameter("userId", userId);
			List<String> sysIds = qc.list();
			if (sysIds == null || sysIds.size() == 0) {
				// 原本没有权限则加
				addSys.add(sRole.getSysId());
			} else {
				// 如有则对比
				boolean flag = true;
				for (String oldsysId : sysIds) {
					if (sRole.getSysId().equals(oldsysId)) {
						// 对比成功，则不添加该系统
						flag = false;
					}
				}
				if (flag) {
					addSys.add(sRole.getSysId());
				}
			}
		}
	}

}